import { useState, useCallback, useRef, useEffect } from 'react';
import { useTVEventHandler } from 'react-native';

export type FocusableElement = 'tab' | 'card' | 'button' | 'refresh' | 'scan';

export interface FocusState {
  currentElement: FocusableElement;
  currentIndex: number;
  tabIndex: number;
  cardIndex: number;
}

export interface FocusManagerOptions {
  onElementChange?: (element: FocusableElement, index: number) => void;
  onCardSelect?: (index: number) => void;
  onTabChange?: (index: number) => void;
  onAction?: (action: string) => void;
  onFocusChange?: (focusState: FocusState) => void;
}

export const useFocusManager = (options: FocusManagerOptions = {}) => {
  const [focusState, setFocusState] = useState<FocusState>({
    currentElement: 'tab',
    currentIndex: 0,
    tabIndex: 0,
    cardIndex: 0,
  });

  const [tabs, setTabs] = useState<string[]>(['local']);
  const [currentCards, setCurrentCards] = useState<any[]>([]);
  const [buttons] = useState(['scan', 'refresh', 'random', 'toggle']);

  // 更新 tabs 列表
  const updateTabs = useCallback((newTabs: string[]) => {
    setTabs(newTabs);
  }, []);

  // 焦点导航逻辑
  const navigateFocus = useCallback((direction: 'up' | 'down' | 'left' | 'right') => {
    setFocusState(prev => {
      const newState = { ...prev };

      switch (prev.currentElement) {
        case 'tab':
          if (direction === 'down') {
            newState.currentElement = 'card';
            newState.currentIndex = 0;
          } else if (direction === 'right' && prev.tabIndex < tabs.length - 1) {
            newState.tabIndex = prev.tabIndex + 1;
            // 当 Tab 切换时，延迟调用回调，避免立即触发状态更新
            setTimeout(() => options.onTabChange?.(newState.tabIndex), 100);
          } else if (direction === 'left' && prev.tabIndex > 0) {
            newState.tabIndex = prev.tabIndex - 1;
            // 当 Tab 切换时，延迟调用回调，避免立即触发状态更新
            setTimeout(() => options.onTabChange?.(newState.tabIndex), 100);
          } else if (direction === 'right' && prev.tabIndex === tabs.length - 1) {
            // 如果是最右边的 Tab，右键切换到按钮
            newState.currentElement = 'button';
            newState.currentIndex = 0;
          }
          break;

        case 'card':
          if (direction === 'up') {
            newState.currentElement = 'tab';
            newState.currentIndex = prev.tabIndex;
          } else if (direction === 'down') {
            newState.currentElement = 'button';
            newState.currentIndex = 0;
          } else if (direction === 'left' && prev.cardIndex > 0) {
            newState.cardIndex = prev.cardIndex - 1;
            newState.currentIndex = prev.cardIndex - 1;
          } else if (direction === 'right' && prev.cardIndex < currentCards.length - 1) {
            newState.cardIndex = prev.cardIndex + 1;
            newState.currentIndex = prev.cardIndex + 1;
          }
          break;

        case 'button':
          if (direction === 'down') {
            newState.currentElement = 'card';
            newState.currentIndex = 0;
          } else if (direction === 'left' && prev.currentIndex > 0) {
            newState.currentIndex = prev.currentIndex - 1;
          } else if (direction === 'right' && prev.currentIndex < buttons.length - 1) {
            newState.currentIndex = prev.currentIndex + 1;
          } else if (direction === 'left' && prev.currentIndex === 0) {
            // 如果是最左边的按钮，左键切换到 Tab
            newState.currentElement = 'tab';
            newState.currentIndex = tabs.length - 1; // 切换到最右边的 Tab
          }
          break;
      }

      // 调用焦点状态变化回调，延迟执行避免循环
      setTimeout(() => options.onFocusChange?.(newState), 50);

      return newState;
    });
  }, [tabs, currentCards, buttons, options]);

  // 处理按键事件
  useTVEventHandler((evt: any) => {
    const { eventType } = evt;
    
    switch (eventType) {
      case 'up':
        navigateFocus('up');
        break;
      case 'down':
        navigateFocus('down');
        break;
      case 'left':
        navigateFocus('left');
        break;
      case 'right':
        navigateFocus('right');
        break;
      case 'select':
      case 'enter':
        handleSelect();
        break;
      case 'back':
        handleBack();
        break;
    }
  });

  const handleSelect = useCallback(() => {
    const { currentElement, currentIndex, tabIndex, cardIndex } = focusState;
    
    switch (currentElement) {
      case 'tab':
        options.onTabChange?.(tabIndex);
        break;
      case 'card':
        options.onCardSelect?.(currentIndex);
        break;
      case 'button':
        const buttonAction = buttons[currentIndex];
        // 按钮按下时，先执行动作
        options.onAction?.(buttonAction);
        
        // 根据按钮类型决定是否切换焦点
        if (buttonAction === 'refresh' || buttonAction === 'random' || buttonAction === 'toggle') {
          // 刷新、随机和文字按钮按下后保持在按钮上，不切换焦点
          console.log(`🔄 ${buttonAction === 'refresh' ? '刷新' : buttonAction === 'random' ? '随机' : '文字'}按钮按下，保持在按钮焦点`);
        } else {
          // 其他按钮按下后切换到卡片聚焦
          const newState = {
            currentElement: 'card' as FocusableElement,
            currentIndex: 0,
            tabIndex: tabIndex,
            cardIndex: 0,
          };
          setFocusState(newState);
          // 手动触发焦点状态变化回调
          setTimeout(() => options.onFocusChange?.(newState), 0);
        }
        break;
    }
  }, [focusState, options, buttons]);

  const handleBack = useCallback(() => {
    setFocusState(prev => {
      if (prev.currentElement === 'card') {
        return { ...prev, currentElement: 'tab', currentIndex: prev.tabIndex };
      } else if (prev.currentElement === 'button') {
        return { ...prev, currentElement: 'card', currentIndex: prev.cardIndex };
      }
      return prev;
    });
  }, []);

  // 更新当前卡片数据
  const updateCards = useCallback((cards: any[]) => {
    setCurrentCards(cards);
    // 不改变当前的焦点状态，只是更新数据
    console.log(`📦 更新卡片列表，共 ${cards.length} 张卡片，当前焦点状态保持不变`);
  }, []);

  // 设置焦点到指定元素
  const setFocus = useCallback((element: FocusableElement, index: number = 0) => {
    setFocusState(prev => ({
      ...prev,
      currentElement: element,
      currentIndex: index,
    }));
  }, []);

  // 获取焦点状态
  const getFocusState = useCallback(() => focusState, [focusState]);

  // 检查元素是否被聚焦
  const isFocused = useCallback((element: FocusableElement, index: number = 0) => {
    return focusState.currentElement === element && focusState.currentIndex === index;
  }, [focusState]);

  return {
    focusState,
    navigateFocus,
    updateCards,
    updateTabs,
    setFocus,
    getFocusState,
    isFocused,
    tabs,
    buttons,
  };
}; 